<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系统监控 - BTools</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <div class="container-fluid mt-3">
        <h2>系统资源监控</h2>
        
        <!-- 告警面板 -->
        <div id="alertPanel" class="alert alert-warning d-none" role="alert">
        </div>

        <!-- 资源使用概览 -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">CPU使用率</h5>
                        <div class="progress">
                            <div id="cpuProgress" class="progress-bar" role="progressbar" style="width: 0%"></div>
                        </div>
                        <p id="cpuText" class="mt-2 mb-0">0%</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">内存使用率</h5>
                        <div class="progress">
                            <div id="memoryProgress" class="progress-bar" role="progressbar" style="width: 0%"></div>
                        </div>
                        <p id="memoryText" class="mt-2 mb-0">0%</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">磁盘使用率</h5>
                        <div class="progress">
                            <div id="diskProgress" class="progress-bar" role="progressbar" style="width: 0%"></div>
                        </div>
                        <p id="diskText" class="mt-2 mb-0">0%</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">网络流量</h5>
                        <p id="networkText" class="mb-0">↑ 0 KB/s ↓ 0 KB/s</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 图表 -->
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">CPU使用率历史</h5>
                        <canvas id="cpuChart"></canvas>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">内存使用率历史</h5>
                        <canvas id="memoryChart"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- 进程列表 -->
        <div class="card">
            <div class="card-body">
                <h5 class="card-title">Top 进程</h5>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>PID</th>
                                <th>进程名</th>
                                <th>CPU使用率</th>
                                <th>内存使用率</th>
                            </tr>
                        </thead>
                        <tbody id="processTable">
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 图表配置
        const chartConfig = {
            type: 'line',
            data: {
                labels: [],
                datasets: [{
                    label: '使用率 (%)',
                    data: [],
                    borderColor: 'rgb(75, 192, 192)',
                    tension: 0.1
                }]
            },
            options: {
                responsive: true,
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 100
                    }
                }
            }
        };

        // 初始化图表
        const cpuChart = new Chart(
            document.getElementById('cpuChart'),
            JSON.parse(JSON.stringify(chartConfig))
        );
        const memoryChart = new Chart(
            document.getElementById('memoryChart'),
            JSON.parse(JSON.stringify(chartConfig))
        );

        // 更新函数
        function updateCharts(data) {
            const timestamp = data.timestamp.split(' ')[1];
            
            // 更新CPU图表
            if (cpuChart.data.labels.length > 30) {
                cpuChart.data.labels.shift();
                cpuChart.data.datasets[0].data.shift();
            }
            cpuChart.data.labels.push(timestamp);
            cpuChart.data.datasets[0].data.push(data.cpu.percent);
            cpuChart.update();

            // 更新内存图表
            if (memoryChart.data.labels.length > 30) {
                memoryChart.data.labels.shift();
                memoryChart.data.datasets[0].data.shift();
            }
            memoryChart.data.labels.push(timestamp);
            memoryChart.data.datasets[0].data.push(data.memory.percent);
            memoryChart.update();

            // 更新进度条
            document.getElementById('cpuProgress').style.width = `${data.cpu.percent}%`;
            document.getElementById('cpuText').textContent = `${data.cpu.percent.toFixed(1)}%`;
            
            document.getElementById('memoryProgress').style.width = `${data.memory.percent}%`;
            document.getElementById('memoryText').textContent = `${data.memory.percent.toFixed(1)}%`;
            
            document.getElementById('diskProgress').style.width = `${data.disk.percent}%`;
            document.getElementById('diskText').textContent = `${data.disk.percent.toFixed(1)}%`;

            // 更新网络信息
            const bytesToMB = bytes => (bytes / (1024 * 1024)).toFixed(2);
            document.getElementById('networkText').textContent = 
                `↑ ${bytesToMB(data.network.bytes_sent)} MB ↓ ${bytesToMB(data.network.bytes_recv)} MB`;

            // 更新进程表
            const processTable = document.getElementById('processTable');
            processTable.innerHTML = data.processes.map(proc => `
                <tr>
                    <td>${proc.pid}</td>
                    <td>${proc.name}</td>
                    <td>${proc.cpu_percent.toFixed(1)}%</td>
                    <td>${proc.memory_percent.toFixed(1)}%</td>
                </tr>
            `).join('');

            // 更新告警
            const alertPanel = document.getElementById('alertPanel');
            if (data.alerts && data.alerts.length > 0) {
                alertPanel.textContent = data.alerts.join('; ');
                alertPanel.classList.remove('d-none');
            } else {
                alertPanel.classList.add('d-none');
            }
        }

        // 定时获取数据
        async function fetchMetrics() {
            try {
                const response = await fetch('/sysmon/metrics');
                const data = await response.json();
                if (data.length > 0) {
                    updateCharts(data[data.length - 1]);
                }
            } catch (error) {
                console.error('Error fetching metrics:', error);
            }
        }

        // 每2秒更新一次数据
        setInterval(fetchMetrics, 2000);
    </script>
</body>
</html>
